<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\admin\model\Cart;
use think\Db;
use app\admin\model\Product;
use app\admin\model\Order as ModelOrder;
use app\admin\model\order\Goods;


use addons\csmding\library\dingtalk\DingTalkClient;
use addons\csmding\library\dingtalk\DingTalkConstant;
use addons\csmding\library\dingtalk\OapiUserGetuserinfoRequest;
use addons\csmding\library\Csmding;

/**
 * 首页接口
 */
class Dingding extends Api
{
    protected $noNeedLogin = ['login','getUserInfoByCode'];
    // protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    //购物车列表
    public function cart()
    {
        $user_id = $this->auth->id ?? 1;
        $list = Cart::with('product')->where('user_id',$user_id)->select();
        foreach($list as $row){
            $row->getRelation('product')->visible(['product_name','image_urls']);

            if(!empty($row->product->image_urls)){
                $image_urls = explode(',',$row->product->image_urls);
                $row->product->image_urls = $image_urls[0];
            }
        }
        $this->success('ok',$list);
    }
public function product_cate(){
    $product_category = Db::name('product_category')->column('name');
    $product_set = Db::name('product_set')->column('id,product_set_name');
    $supplier = Db::name('supplier')->column('id,supplier_name');
    $product_material = Db::name('product_material')->column('name');
    $product_purity = Db::name('product_purity')->column('name');
    $product_technology = Db::name('product_technology')->column('name');
    $product_skn = Db::name('product_skn')->column('name');
    $list = compact('product_category','product_set','product_material','product_purity','product_technology','product_skn');
    $this->success('ok',$list); 
}

    //修改购物车
    public function cart_edit()
   {
       //设置过滤方法
   
           $user_id = $this->auth->id ?? 1;
           $return = '';
           $type = input('type');
           $product_id = input('product_id');
           $cart_id = input('cart_id');
           $product_material = input('product_material');
           $product_purity = input('product_purity');
           $product_technology = input('product_technology');
           $product_skn = input('product_skn');
           $material_weight = input('material_weight');
           
           $num = input('num',1);
           // 清空购物车
           if($type== 'empty'){
               (new Cart())->where(['user_id' => $this->auth->id])->delete();
           // 新增购物车
           }else if($type== 'add'){
               $where = [
                   'product_id' => $product_id,
                   'product_material' => $product_material,
                   'product_purity' => $product_purity,
                   'product_technology' => $product_technology,
                   'product_skn' => $product_skn,
                   'material_weight' => $material_weight,
                   'user_id' => $user_id
               ];
               // 查询是否已存在，如果已存在只改变数量和总价
               $cart = (new Cart())->where($where)->find();
               if($cart){
                   $num += $cart['num'];
                   $params = [
                       'num' => $num,
                   ];
                   $cart->save($params);
               }else{
                   // 只新增ID，1.0.2升级
                   $where['num'] = $num;
                   (new Cart())->save($where, false);
               }
           // 新增购物车
           }else if($type== 'change'){
               $where = [
                   'id' => $cart_id,
               ];
               $cart = (new Cart())->where($where)->find();
               // 1.0.5升级
               $cart->save(['num' => $num]);
           // 批量删除
           }else if($type== 'del'){	
            $cart_id = $cart_id;
            $cart_id = explode(',',$cart_id);
               foreach ($cart_id as $row) {
                   $where = [
                       'id' => $row,
                   ];
                   (new Cart())->where($where)->delete();
               }
           // 先将传来的批量写进关注表，在删除这些
           }else{
               $this->error(__('网络繁忙'));
           }
           $this->success('更新购物车完成！', $return);
   }

          // 收藏
          public function love(){
            $user_id = $this->auth->id ?? 1;
            $id = input('id');
            $product_ids = Db::name('user')->where('id',$user_id)->value('love_ids');
            $product_ids = explode(',',$product_ids);
            $i = 0;
            if(in_array($id,$product_ids)){
                foreach($product_ids as $k=>&$v){
                    if($v==$id){
                        unset($product_ids[$k]);
                    }
                }
            }else{
                $product_ids[]= $id;
                  $i = 1;

            }
            $product_ids = implode(',',$product_ids);
            $product_ids = Db::name('user')->where('id',$user_id)->update(['love_ids'=>$product_ids]);
            if($i){
                $this->success('收藏成功');
            }else{
                $this->success('取消收藏');
            }

        }
        public function love_list(){
            $user_id = $this->auth->id ?? 1;
            $love_ids = Db::name('user')->where('id',$user_id)->value('love_ids');
            if(!$love_ids){
                $this->success('ok',[]);
            }
            $ids = explode(',',trim($love_ids));
            $is_str = ','.implode($ids);
            if($ids){
                $list = (new Product())->whereIn('id',$ids)->orderRaw('field (id '.$is_str.')')->where('is_deleted','N')->paginate();
                foreach ($list as $info) {
                    $info->image_urls = cdnurl($info->image_urls,true);
                }
            }
            $this->success('ok',$list);
        }
        public function product(){
            $id = input('product_id');
            $info = (new Product)->get($id);
            $user_id = $this->auth->id ?? 1;
            $love_ids = Db::name('user')->where('id',$user_id)->value('love_ids');
            $love_ids = explode(',',$love_ids);
            $product_set = Db::name('product_set')->column('id,product_set_name');
            if($info){
                $info->image_urls = cdnurl($info->image_urls,true);
                if(in_array($id,$love_ids)){
                    $info->is_love = 1;
                }else{
                    $info->is_love = 0;
                }
                if(!empty($product_set[$info->product_set])){
                    $info->product_set = $product_set[$info->product_set];
                }
                if(!empty($info->product_material)){
                    $info->product_material = explode(',',$info->product_material);
                }
                if(!empty($info->material_weight)){
                    $info->material_weight = explode(',',$info->material_weight);
                }
                if(!empty($info->image_urls)){
                    $image_urls = explode(',',$info->image_urls);
                    $info->image_urls = cdnurl($image_urls[0],true);
                }
                if(!empty($info->product_purity)){
                    $info->product_purity = explode(',',$info->product_purity);
                }
                if(!empty($info->product_technology)){
                    $info->product_technology = explode(',',$info->product_technology);
                }
                if(!empty($info->product_skn)){
                    $info->product_skn = explode(',',$info->product_skn);
                }
              $this->success('ok',$info);
            }else{
                $this->error('商品已下架');
            }
        }
        
        //展示
        public function product_list(){
            $op['supplier_id'] =['>=',0];
            $op['is_deleted'] = 'N';
            $user_id = $this->auth->id ?? 1;
            $product_category = input('product_category');
            $keywords = input('keywords');
            $where = ' 1 ';
            if($product_category){
                $op['product_category'] = $product_category;
            }
            if($keywords){
                $op['product_name'] = ['like','%'.$keywords.'%'];
            }
            $product_material = input('product_material');
            if($product_material){
                $where .= ' and FIND_IN_SET("'.$product_material.'",product_material) ';

            }
            $product_purity = input('product_purity');
            if($product_purity){
                $where .= ' and FIND_IN_SET("'.$product_purity.'",product_purity) ';

            }
            $product_technology = input('product_technology');
            if($product_technology){
                $where .= ' and FIND_IN_SET("'.$product_technology.'",product_technology) ';

            }
            $product_skn = input('product_skn');
            if($product_skn){
                $where .= ' and FIND_IN_SET("'.$product_skn.'",product_skn) ';
            }
            $product_set = input('product_set');
            if($product_set){
                $op['product_set'] = $product_set;
                unset($op['supplier_id']);
            }
            $list = (new Product)->where($op)->where($where)->paginate(10);
            $love_ids = Db::name('user')->where('id',$user_id)->value('love_ids');
            $love_ids = explode(',',$love_ids);
            foreach ($list as $info) {
                if(in_array($info->id,$love_ids)){
                    $info->is_love = 1;
                }else{
                    $info->is_love = 0;
                }
                if(!empty($info->image_urls)){
                    $image_urls = explode(',',$info->image_urls);
                    $info->image_urls =  cdnurl($image_urls[0],true);
                }
                if(!empty($info->product_material)){
                    $product_material = explode(',',$info->product_material);
                    $info->product_material =  $product_material[0];
                }
                if(!empty($info->material_weight)){
                    $material_weight = explode(',',$info->material_weight);
                    $info->material_weight =  $material_weight[0];
                }
            }
            $this->success('ok',$list);
        }





          // 确认收货
    // 1 已提交 2 已审核 3 已发送 4已完成
    public function order_confim(){
        $id = input('id');
        $info =(new ModelOrder())->get($id);
        // if($info['admin_id'] != $this->auth->id){
        //     return json_encode(['code'=>0,'msg'=>"非本人操作"]);
        // }
        if($info['status'] == 4){
            $this->error('订单已确认收货');
        }
        if($info['status'] != 3){
            $this->error('不可操作');
        }
        $info->status= 4;
        $info->endtime = time();
        $info->save();
        $this->success('操作成功');
    }

    public function order_del(){
        $id = input('id');
        $info =(new ModelOrder())->get($id);
        if(!$info){
            $this->error('订单不存在');
        }
        if($info['status'] != 1){
            $this->error('不可操作');
        }
        $info->delete();
        $this->success('操作成功');
    }

    public function login()
    {
          $code = $this->request->request("code");
          trace("=loginTmpCode1>{$code}");
            $respdduser = $this->getUserInfoByCode($code);
            trace("=loginTmpCode2>{$respdduser->errcode}");
            if ($respdduser != null && $respdduser->errcode == 0) {
                $dao = new \app\admin\model\csmding\Dduser();
                $row = $dao->where('userid', '=', $respdduser->userid)->find();
                // Db::name('aa')->insert(['query'=>json_encode($respdduser)]);
                if ($row != null) {
                    if($row->fauser_id){
                        $this->auth->direct($row->fauser_id);
                        $data = ['userinfo' => $this->auth->getUserinfo()];
                        $this->success('ok',$data);
                }
            }
            $this->error('当前账号不可登录手机端,请联系管理员同步通讯录！');
    }else{
        $this->error($respdduser->errcode.':'.$respdduser->errmsg);
    }
}


private static function getUserInfoByCode($code)
{
    $access_token = Csmding::getAccessToken();

    $c = new DingTalkClient(DingTalkConstant::$CALL_TYPE_OAPI, DingTalkConstant::$METHOD_GET, DingTalkConstant::$FORMAT_JSON);
    $req = new OapiUserGetuserinfoRequest();
    $req->setCode($code);
    $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/user/getuserinfo");
    return $resp;
}



    

    public function addOrder(){
        $cart_ids = input('cart_ids');
        $cart_ids = explode(',',$cart_ids);
        $list = (new Cart())::with('product')->whereIn('cart.id',$cart_ids)->select();
        if(!$list){
                $this->error('商品已下架');
        }else{
            $order_no = rand(100,999).time();
            $nums = (new Cart())::with('product')->whereIn('cart.id',$cart_ids)->sum('num');
            $user_id = $this->auth->id ?? 1;
            $order = (new ModelOrder());
            $depart = DB::name('user')->where('id',$this->auth->id)->value('depart');
            $order->save(compact('order_no','nums','user_id','depart'));
            $narr = [];
            foreach($list as $v){
                if(!empty($v->product->image_urls)){
                    $image_urls = explode(',',$v->product->image_urls);
                    $v->product->image_urls = cdnurl($image_urls[0],true);
                }
                $narr[] = [
                    'user_id'=>$user_id,
                    'product_id'=>$v->product_id,
                    'nums'=>$v->num,
                    'order_id'=>$order->id,
                    'image_urls'=>$v->product->image_urls,
                    'product_name'=>$v->product->product_name,
                    'supplier_id'=>$v->product->supplier_id,
                    'product_code'=>$v->product->product_code,
                    'product_category'=>$v->product->product_category,
                    'product_purity'=>$v->product_purity,
                    'material_weight'=>$v->material_weight,
                    'product_material'=>$v->product_material,
                    'product_technology'=>$v->product_technology,
                    'product_skn'=>$v->product_skn,
                ];
            }
            (new Goods())->saveAll($narr);
        }
        (new Cart())::whereIn('id',$cart_ids)->delete();
        $this->success('ok');

    }
    // 订单详情
    public function order_detail(){
        $id = input('id');
        $order = (new ModelOrder)->where('id',$id)->find();
        $order_item = (new Goods())->where('order_id',$id)->select();
        foreach($order_item as $v){
            $v->image_urls = cdnurl($v->image_urls,true);
        }
        $data = compact('order','order_item');
        $this->success('ok',$data);
    }
    // 订单列表
    public function order_list(){
        $user_id = $this->auth->id ?? 1;
        $op['user_id'] = $user_id;

        $status = input('status');
        if($status){
            $op['status'] = $status;
        }
        $order = (new ModelOrder)->where($op)->order('id desc')->paginate();
        $this->success('ok',$order);
    }



}
